<script lang="ts" setup>
import { reactive, ref } from 'vue'
import api from '/@/api/email/index';
import { type FormInstance, type FormRules } from 'element-plus'

defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
})
const emit = defineEmits(['update:modelValue', 'refresh'])
const ruleFormRef = ref<FormInstance>()
const currentMax = ref(0)
interface RuleForm {
    orderId: number | undefined
    factoryId: number | undefined
    goodsAmount: number | undefined
    remark: string
}
const ruleForm = reactive({
    orderId: undefined,
    factoryId: undefined,
    goodsAmount: undefined,
    remark: '',
})
const rules = reactive<FormRules<RuleForm>>({
    goodsAmount: [{ required: true, message: '请填写付款金额', trigger: 'change' }],
})
const submit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            const obj: RuleForm = { ...ruleForm }
            const { code } = await api.order.addRefund(obj)
                if (code === 200) {
                    ElMessage.success('退款成功')
                    emit('refresh')
                    close()
                }
        } else {
            console.log('error submit!', fields)
        }
    })
}
const close = () => {
    ruleFormRef.value?.resetFields()
    emit('update:modelValue', false)
}

defineExpose({
    ruleForm,
    currentMax
})
</script>
<template>
    <TwoDialog id="addRefund" :modelValue="modelValue" title="退款" width="520px" @submit="submit(ruleFormRef)" @close="close" @minimize="emit('update:modelValue', false)">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
            <el-row :gutter="16">
                <el-col :span="24">
                    <el-form-item label="退款金额" prop="goodsAmount">
                        <el-input-number v-model="ruleForm.goodsAmount" :min="0" :max="currentMax" :step="0.001" :precision="2" :controls="false" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="ruleForm.remark" type="textarea" placeholder="请填写备注"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </TwoDialog>
</template>
<style lang="scss" scoped>
.cascader-panel {
    width: fit-content;
}
</style>